package com.aglow.bluetoothspeaker.utils;


import android.graphics.Color;
import android.util.Log;

import com.actions.ibluz.factory.IBluzDevice;
import com.actions.ibluz.manager.BluzManager;
import com.actions.ibluz.manager.BluzManagerData;
import com.actions.ibluz.manager.IAlarmManager;
import com.actions.ibluz.manager.IAuxManager;
import com.actions.ibluz.manager.IBluzManager;
import com.actions.ibluz.manager.IRadioManager;
import com.aglow.bluetoothspeaker.app.App;
import com.aglow.bluetoothspeaker.model.cache.MusicCache;
import com.aglow.bluetoothspeaker.model.event.BluzManagerReadyEvent;
import com.aglow.bluetoothspeaker.model.event.CustomCommandEvent;
import com.aglow.bluetoothspeaker.model.event.ModeChangedEvent;
import com.aglow.bluetoothspeaker.model.event.VolumeChangedEvent;
import com.orhanobut.logger.BuildConfig;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

/**
 * @author 尹晓童
 * 邮箱：yinxtno1@yeah.net
 * 时间：2017/11/18
 * 作用：BluzManager 的封装工具类
 */

public class BluzManagerUtils {

    private final int KEY_LED_SET = BluzManager.buildKey(BluzManagerData.CommandType.SET, 0x81);
    private final int KEY_TIME_SET = BluzManager.buildKey(BluzManagerData.CommandType.SET, 0x00);
    private final int KEY_LED_MODE_SET = BluzManager.buildKey(BluzManagerData.CommandType.SET, 0x82);
    private final int KEY_LED_STATE_SET = BluzManager.buildKey(BluzManagerData.CommandType.SET, 0x83);

    //灯控状态相关
    public static final int KEY_QUE_LIGHT_CONTROL_STATE = BluzManager.buildKey(BluzManagerData.CommandType.QUE, 0x81);
    public static final int KEY_ANS_LIGHT_CONTROL_STATE = BluzManager.buildKey(BluzManagerData.CommandType.ANS, 0x81);

    //时间查询
    public static final int KYE_QUE_TIME_QUE_STATE = BluzManager.buildKey(BluzManagerData.CommandType.QUE, 0x12);
    public static final int KYE_ANS_TIME_ANS_STATE = BluzManager.buildKey(BluzManagerData.CommandType.QUE, 0x12);


    //查询闹钟
    public static final int KEY_QUE_ALARMS_TIME = BluzManager.buildKey(BluzManagerData.CommandType.QUE, 0x14);
    public static final int KEY_ANS_ALARMS_TIME = BluzManager.buildKey(BluzManagerData.CommandType.QUE, 0x14);

    //查询闹钟列表
    public static final int KEY_ANS_ALARMS_TIME_LIST = BluzManager.buildKey(BluzManagerData.CommandType.ANS, 0x30);
    private static final int KEY_ALARM_ID_QUE = BluzManager.buildKey(BluzManagerData.CommandType.QUE, 0x30);

    private BluzManager mBluzManager;

    private boolean uhostEnable = false;

    private int curMode;

    private BluzManagerUtils() {
    }

    private static final class Holder {
        final static BluzManagerUtils INSTANCE = new BluzManagerUtils();
    }

    public static BluzManagerUtils getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 创建 BluzManager
     *
     * @param device IBluzDevice
     */
    public void createBluzManager(IBluzDevice device) {
        uhostEnable = false;
        Log.i("main", "mBluzManager = " + mBluzManager);
        if (device != null && mBluzManager == null) {
            mBluzManager = new BluzManager(App.getContext(), device, new BluzManagerData.OnManagerReadyListener() {
                @Override
                public void onReady() {
                    mBluzManager.setSystemTime();
                    setForeground(true);
                    EventBus.getDefault().post(new BluzManagerReadyEvent());
                    Log.i("main", "Device utils = " + device);
                    mBluzManager.setOnGlobalUIChangedListener(new BluzManagerData.OnGlobalUIChangedListener() {
                        @Override
                        public void onEQChanged(int eq) {
                        }

                        @Override
                        public void onBatteryChanged(int battery, boolean inCharge) {
                        }

                        @Override
                        public void onVolumeChanged(int volume, boolean mute) {
                            SpManager.getInstance().saveCurrentVolume(volume);
                            EventBus.getDefault().post(new VolumeChangedEvent(volume, mute));
                        }

                        @Override
                        public void onModeChanged(int mode) {
                            Logger.d("onModeChanged   mode == " + mode);
                            curMode = mode;
                            EventBus.getDefault().post(new ModeChangedEvent(mode));
                        }
                    });

                    mBluzManager.setOnHotplugChangedListener(new BluzManagerData.OnHotplugChangedListener() {
                        @Override
                        public void onCardChanged(boolean b) {

                        }

                        @Override
                        public void onUhostChanged(boolean b) {
                            uhostEnable = b;
//                            HotplugChangedEvent event = new HotplugChangedEvent();
//                            event.setUhostEnable(b);
//                            EventBus.getDefault().post(event);
                        }

                        @Override
                        public void onLineinChanged(boolean b) {

                        }

                        @Override
                        public void onUSBSoundChanged(boolean b) {

                        }
                    });

                    setOnCustomCommandListener();
                }
            });

        }
    }

    public boolean isUhostEnable() {
        return uhostEnable;
    }

    public void setOnGlobalUIChangedListener(BluzManagerData.OnGlobalUIChangedListener listener) {
        if (mBluzManager == null) {
            return;
        }
        mBluzManager.setOnGlobalUIChangedListener(listener);
    }

    public BluzManager getBluzManager() {
        return mBluzManager;
    }
    public IBluzManager getIBluzManager() {

        return mBluzManager;
    }

    /**
     * 释放
     */
    public void release() {
        if (mBluzManager == null) {
            return;
        }
        uhostEnable = false;
        mBluzManager.release();
        mBluzManager = null;
    }

    /**
     * 设置模式
     *
     * @param mode 模式
     */
    public void setMode(int mode) {
        if (mBluzManager == null) {
            return;
        }
//        if (mode != BluzManagerData.FuncMode.A2DP && MusicCache.getPlayService().isPlaying()) {
//            MusicCache.getPlayService().playPause();
//        }
        mBluzManager.setMode(mode);
    }

    public int getCurrentMode() {
        return curMode;
    }

    public void setSystemTime() {
        if (mBluzManager == null) {
            return;
        }
        mBluzManager.setSystemTime();
    }

    public void setForeground(boolean foreground) {
        if (mBluzManager == null) {
            return;
        }
        mBluzManager.setForeground(foreground);
    }

    public IAuxManager getAuxManager(BluzManagerData.OnManagerReadyListener listener) {
        if (mBluzManager == null) {
            return null;
        }
        return mBluzManager.getAuxManager(listener);
    }

    /**
     * 设置音量
     *
     * @param volume 音量
     */
    public void setVolume(int volume) {
        if (mBluzManager == null) {
            return;
        }
        mBluzManager.setVolume(volume);
    }

    /**
     * 获取当前音量，从本地缓存获取
     *
     * @return 当前音量
     */
    public int getCurrVolume() {
        return SpManager.getInstance().getCurrentVolume();
    }

    /**
     * 查询led
     */
    public void queryLed() {
        sendCustomCommand(KEY_QUE_LIGHT_CONTROL_STATE, 0, 0, null);
        Log.i("led", "查询led");
    }

    /**
     * 获取最大音量
     *
     * @return 最大音量
     */
    public int getMaxVolume() {
        if (mBluzManager == null) {
            return 0;
        }
        return mBluzManager.getMaxVolume();
    }

    public boolean isContentChanged() {
        if (mBluzManager == null) {
            return false;
        }
        return mBluzManager.isContentChanged();
    }

    public IRadioManager getRadioManager(BluzManagerData.OnManagerReadyListener listener) {
        if (mBluzManager == null) {
            return null;
        }
        return mBluzManager.getRadioManager(listener);
    }

    public void setOnCustomCommandListener() {
        if (mBluzManager == null) {
            return;
        }
        mBluzManager.setOnCustomCommandListener((what, param1, param2, bytes) -> {
            if (BuildConfig.DEBUG) {
            if (bytes == null) {
                Logger.d("param1：" + param1 + "   param2: " + param2 + "\n数据：null");
            } else {
                Logger.d("param1：" + param1 + "   param2: " + param2
                        + "\n数据：" + HexUtils.bytes2hex(bytes));
            }
            }
            EventBus.getDefault().post(new CustomCommandEvent(what, param1, param2, bytes));
        });

    }

    public void setOnCustomCommandListener(BluzManagerData.OnCustomCommandListener listener) {
        if (mBluzManager == null) {
            return;
        }
        mBluzManager.setOnCustomCommandListener(listener);
    }

    /**
     * 打开、关闭 LED 灯
     */
    public void openOrCloseLed() {
        sendCommand(0x54);
    }


    /**
     * 发送颜色
     *
     * @param red   红
     * @param green 绿
     * @param blue  蓝
     * @param mode  0x01 常规模式 0x02 呼吸模式 0x03律动模式
     */
    public void sendColor(int mode, int red, int green, int blue) {
        byte[] buff = new byte[4];
        buff[0] = (byte) (blue & 0xFF);
        buff[1] = (byte) (green & 0xFF);
        buff[2] = (byte) (red & 0xFF);
        buff[3] = (byte) (mode & 0xFF);
        int dataInt = (buff[0] & 0xFF) << 24
                | (buff[1] & 0xFF) << 16
                | (buff[2] & 0xFF) << 8
                | (buff[3] & 0xFF);
//        b 0xE8        g 0xA3       r 0x00      m 0x01  -->0xEBA30001
        Log.i("index", "16进制dataInt = " + dataInt);
        Log.i("index", "16进制dataInt = " + Integer.toHexString(dataInt));
        sendCustomCommand(KEY_LED_MODE_SET, dataInt, 0, null);
    }


    /**
     * 发送亮度
     *
     * @param brightness 亮度 0 -255
     */
    public void sendBrightness(int brightness) {
        sendCustomCommand(KEY_LED_SET, (byte) brightness, 0, null);
    }

    /**
     * 灯光开关控制
     *
     * @param state 01-开灯 00关灯
     */
    public void setLightState(int state) {
        sendCustomCommand(KEY_LED_STATE_SET, (byte) state, 0, null);
    }

    /**
     * 查询闹钟列表
     */
    public void queryAlarmList() {
        sendCustomCommand(KEY_ALARM_ID_QUE, 0, 0, null);
        Log.i("utils","key = "+KEY_ALARM_ID_QUE);
    }

    /**
     * 时间校对
     *
     * @param year
     * @param month
     * @param day
     * @param hour
     * @param minute
     */
    public void checkTime(int year, int month, int day, int hour, int minute, int second) {
        sendTimeCommand((byte) year, (byte) month, (byte) day, (byte) hour, (byte) minute, (byte) second);
    }


    public void sendCommand(int param1, byte... data) {
        sendCustomCommand(KEY_LED_SET, param1, 0, data);
    }

    private void sendTimeCommand(byte... data) {
        sendCustomCommand(KEY_TIME_SET, 0, 0, data);
    }


    public IAlarmManager getAlarmManager(BluzManagerData.OnManagerReadyListener listener) {
        if (mBluzManager == null) {
            return null;
        }

        return mBluzManager.getAlarmManager(listener);

    }

    public void sendCustomCommand(int key, int param1, int param2, byte... data) {
        if (mBluzManager == null) {
            return;
        }
        if (BuildConfig.DEBUG) {
            if (data == null) {
                Logger.d("指令：0x" + Integer.toHexString(param1) + "    数据长度：0\n数据：null");
            } else {
                Logger.d("指令：0x" + Integer.toHexString(param1) + "    数据长度：" + data.length
                        + "\n数据：" + HexUtils.bytes2hex(data));
            }
        }

        mBluzManager.sendCustomCommand(key, param1, param2, data);
    }


}
